#include <iostream>
#include "server.h"
#include "../messages/message.h"
#include <fstream>
#include <stdint.h>
#include <iomanip>
#include <sstream>
#include "../Utils/encode_desencode.h"
#include "../Utils/directoryHandler.h"
#include "../Utils/index.h"
#include "server_configuration.h"
#include <stdio.h>
#include <log4cpp/Category.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/SimpleLayout.hh>
#include <log4cpp/TimeStamp.hh>
#include "server_ui.h"
#include <gtkmm/main.h>
using namespace std;
#define LOGFILE "./Server.log"

log4cpp::Appender *appender = new log4cpp::FileAppender("FileAppender",
		LOGFILE);
log4cpp::Layout *layout = new log4cpp::SimpleLayout();
log4cpp::Category& category = log4cpp::Category::getInstance("Category");

int main(int argc, char** argv) {
	appender->setLayout(layout);
	category.setAppender(appender);
	category.setPriority(log4cpp::Priority::INFO);

	//Obtengo fecha y hora
	time_t rawtime;
	time(&rawtime);
	struct tm * timeinfo = localtime(&rawtime);
	time_t tim = time(NULL);
	tm *now = localtime(&tim);
	category.info("New server log started at %02d:%02d of %02d/%02d/%d",
			now->tm_hour, now->tm_min, now->tm_mday, now->tm_mon + 1,
			now->tm_year + 1900);

	//Path donde se almacena el archivo de properties, carpeta del usuario
	string user_folder(getenv("HOME"));
	category.info("User folder: " + user_folder);
	string properties_file_name("cfg.properties");
	category.info("Properties file name: " + properties_file_name);
	string properties_path = user_folder + "/" + properties_file_name;
	category.info("Properties file path: " + properties_path);

	//Se carga la configuracion
	ServerCfg cfg(&properties_path);

	//Levanto la cfg del archivo
	try {
		cfg.Initialize();
		category.info("Listen for incoming connections at port %d",
				cfg.GetPort());
		category.info("Server storage folder path: " + cfg.GetStoragePath());
		Gtk::Main kit(argc, argv);
		Ui ui(&cfg);
		Gtk::Main::run(ui);
	} catch (const FileNotExist& e) {
		//Si no encuentra el archivo de configuracion, salgo del programa
		category.error(
				"Properties file not found, please run monitor app first");

	}

	category.notice("Program finished.");
	return 0;
}
